<template>
  <div :class="['grid-container', layoutClass]">
    <LiveVideo
      class="grid-item"
      v-for="(video, index) in visibleVideos"
      :key="video.id"
      :url="video.url"
      :id="'video-' + index"
    />
  </div>
</template>

<script setup>
import LiveVideo from './components/liveVideo.vue'
import { computed } from 'vue'
const props = defineProps({
  videos: {
    type: Array,
    default: () => [],
  },
})
// 动态布局
const layoutClass = computed(() => {
  const layouts = [4, 5, 6, 9]
  let len = props.videos.length
  // 找到最接近的宫格布局
  let closestLayout = layouts.reduce((prev, curr) => {
    return Math.abs(curr - len) < Math.abs(prev - len) ? curr : prev
  })
  return `layout-${closestLayout}`
})
// 可见的视频数组
const visibleVideos = computed(() => {
  const videosLength = parseInt(layoutClass.value.split('-')[1])
  return props.videos.slice(0, videosLength)
})
</script>

<style lang="scss" scoped>
.grid-container {
  display: grid;
  gap: 5px;
  width: 100%;
  height: 100%;
}
.grid-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
.layout-4 {
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  /* 等同于 */
  /* grid-template-columns: 1fr 1fr 1fr; */
  /* grid-template-rows: 1fr 1fr; */
}
.layout-5 {
  grid-template-columns: 1fr 1fr; /* 左右各占一半 */
  grid-template-rows: repeat(6, 1fr); /* 上下六行，每行高度相等 */

  .grid-item:nth-child(1) {
    grid-column: 1 / 2;
    // 表示从第1行开始，跨越3行,结果是元素占据从第1行到第4行的位置。
    grid-row: 1 / span 3; /* 占据前3行 */
    // 等价于
    grid-row: 1 / 4;
  }

  .grid-item:nth-child(2) {
    grid-column: 1 / 2;
    grid-row: 4 / span 3; /* 占据后3行 */
  }

  .grid-item:nth-child(3) {
    grid-column: 2 / 3;
    grid-row: 1 / span 2;
  }

  .grid-item:nth-child(4) {
    grid-column: 2 / 3;
    grid-row: 3 / span 2;
  }

  .grid-item:nth-child(5) {
    grid-column: 2 / 3;
    grid-row: 5 / span 2;
  }
}
.layout-6 {
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
}
.layout-9 {
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
}
</style>
